package cn.hg.solon.youcan.framework.web.filter;

import java.util.Date;

import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.http.meta.HttpStatus;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

import cn.hg.solon.youcan.common.annotation.Log;

/**
 * @author 胡高
 */
@Component(index = Integer.MAX_VALUE - 10000)
public class ActionFilter implements Filter {

    /* (non-Javadoc)
     * @see org.noear.solon.core.handle.Filter#doFilter(org.noear.solon.core.handle.Context, org.noear.solon.core.handle.FilterChain)
     */
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        Date start = DateUtil.now();
        try {
            chain.doFilter(ctx);

            // 可能上级链已完成处理
            if (ctx.getHandled()) {
                return;
            }

            if(!ctx.getHandled()){
                ctx.status(HttpStatus.HTTP_NOT_FOUND);
                // 统一的结果处理
                ActionResultHandler.handle(ctx, null);
            }
        } catch (Throwable e) {
            // 统一的异常处理
            ActionResultHandler.handle(ctx, e);
        } finally {
            if (ObjUtil.isNotNull(ctx.action())) {
                Date end = DateUtil.now();
                // 打印Action报告
                ActionReporter.report(ctx, end.getTime() - start.getTime());

                Log log = ctx.action().method().getAnnotation(Log.class);
                if (ObjUtil.isNotNull(log)) {
                    // 对有Log注解的操作记录其操作日志
                    OperateLogReporter.actionLog(ctx, log, start, end);
                }
            }
            UserOnlineSyncHandler.handle(ctx);
        }
    }

}
